package capricornus.utils.roughtime
{
	import capricornus.core.RefreshManager;
	import capricornus.events.RefreshEvent;
	
	import flash.events.EventDispatcher;

	[Event(name="timer", type="capricornus.utils.roughtime.RoughTimerEvent")]
	public class RoughTimer extends EventDispatcher
	{
		private var _currentDuration:uint;
		private var _duration:uint;
		private var _currentTime:int;
		private var _time:int;
		
		private var _hasAdd:Boolean = false;
		
		public function RoughTimer( duration:uint, time:int=0 )
		{
			_duration = duration;
			_time = time;
			_currentTime = _time;
			_currentDuration = 0;
			init();
		}
		
		private function init():void
		{
		}
		
		public function get running():Boolean
		{
			return _hasAdd;	
		}
		
		public function set duration( value:uint ):void
		{
			_duration = value;
		}
		
		public function get duration():uint
		{
			return _duration;
		}
		
		public function reset():void
		{
			_currentTime = _time;
			_currentDuration = 0;
		}
		
		public function start():void
		{
			if( !_hasAdd )
			{
				_hasAdd = true;
				RefreshManager.instance.addEventListener( RefreshEvent.REFRESH, onRefresh, false, 0, true );
			}
		}
		
		public function stop():void
		{
			if( _hasAdd )
			{
				_hasAdd = false;
				RefreshManager.instance.removeEventListener( RefreshEvent.REFRESH, onRefresh );
			}
		}
		
		private function onRefresh( e:RefreshEvent ):void
		{
			_currentDuration += e.data;
			if( _currentDuration >= _duration )
			{
				_currentDuration = 0;
				if( _time != 0 )
				{
					_currentTime--;
					if( _currentTime <= 0 )
					{
						stop();
					}
				}
				dispatchEvent( new RoughTimerEvent( RoughTimerEvent.TIMER ) );
			}
		}
	}
}






